package com.ruoyi.common.core.aspect;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author zhaoYuFei
 */
@Aspect
@Component
public class ThreadAnnotationAspect {

    @Around("@annotation(ThreadAnnotation)")
    public Object handleThreadAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获得方法签名
        String methodName = joinPoint.getSignature().getName();
        // 获取目标对象
        Object target = joinPoint.getTarget();

        // 通过反射调用原方法，并标记为异步执行
        return executeAsync(target, methodName, joinPoint.getArgs());
    }

    @Async
    public Object executeAsync(Object target, String methodName, Object[] args) throws Throwable {
        // 使用反射调用方法
        Method method = target.getClass().getMethod(methodName, null);
        return method.invoke(target, args);
    }
}